package sanduche.play.generators

import java.io.File
import java.io.PrintWriter

object JavascriptGenerator {

  def apply(modules: Seq[SanModule]) {
    modules.map { module =>
      val maybeDirPath = if (module.config.javascriptDirPath().length() > 0)
        Some(module.config.javascriptDirPath())
      else None;

      maybeDirPath.foreach { dirPath =>
        val f = new File(dirPath ++ module.name ++ "-module1.js")
        if (!f.exists()) f.createNewFile();
        val pw = new PrintWriter(f);
        pw.print(toJavascriptModule(module))
        pw.close
      }

    }
  }

  def toJavascriptResourceService(service: SanService, prefix: String) = {
    s"""|		service.${service.simpleName}Resource=$$resource('${prefix ++ service.route.value()}',{},{${service.simpleName}:{method:'${service.route.method()}',isArray:${service.returnType.isIterable}}}).${service.simpleName};
        |		service.${service.simpleName} = function(${
      (service.urlParams.map { param =>
        param.reference
      } ::: service.maybeBody.map { body => body.reference }.toList ::: List("callback", "error")).mkString(", ")
    }) { return service.${service.simpleName}Resource({${
      service.urlParams.map { param =>
        param.reference ++ ":" ++ param.reference
      }.mkString(", ")
    }}, ${service.maybeBody.map(_.reference ++ ", ").getOrElse("")}callback, error); }
      """.stripMargin
  }

  def toJavascriptModule(module: SanModule) = {
    val name = module.name.replaceAll("Controller", "");
    s"""define([ 'ng', 'ngResource' ], function(angular) {
    |		var app=angular.module("${name}Module", [ "ngResource" ]);
    |		app.factory("$name",function($$resource) {
    |		var service = {};
    ${
      module.services.map { service =>
        toJavascriptResourceService(service, module.prefix)
      }.mkString("\n")
    }
    |		return service;
    |	});
    |});
    """.stripMargin
  }

}